/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑, 永无BUG!
 * 　　　　┃　　　┃Code is far away from bug with the animal protecting
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 */
package com.shikSMS.manage.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.google.common.collect.Maps;
import com.shikSMS.constant.SysConstants;
import com.shikSMS.domain.*;
import com.shikSMS.manage.controller.SendController;
import com.shikSMS.manage.service.SmsLogService;
import com.shikSMS.manage.service.SmsSendService;
import com.shikSMS.support.plugin.sms.AliSms;
import com.shikSMS.support.util.sms.SmsParseUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author gengshikun
 * @date 2017/11/28
 */
@Service
@Transactional
public class SmsSendServiceImpl implements SmsSendService {

    private static final Logger logger = LoggerFactory.getLogger(SmsSendServiceImpl.class);

    @Autowired
    private SmsLogService smsLogService;

    @Override
    @Async
    public void sendSms(SmsAuthorize smsAuthorize, String arrPhone, String arrParam) {
        SmsHost smsHost = smsAuthorize.getSmsHost();
        SmsSign smsSign = smsAuthorize.getSmsSign();
        SmsModel smsModel = smsAuthorize.getSmsModel();
        try {
            String phones = SmsParseUtils.decryptByPrivateKey(arrPhone, smsHost.getPrivateKey());
            logger.info(">>>>>>> arrPhone: {} >>>>>>>>>>>", arrPhone);
            phones = phones.substring(1, phones.length() - 1);
            String[] arrPhones = phones.split(", ");

            String model = smsModel.getModelContent();

            Map map = Maps.newHashMap();


            String params = SmsParseUtils.decryptByPrivateKey(arrParam, smsHost.getPrivateKey());
            logger.info(">>>>>>> arrParam: {} >>>>>>>>>>>", arrParam);

//          String params = arrParam;
            if(!StringUtils.equals(params, "null")) {
                params = params.substring(1, params.length() - 1);
                String[] arrParams = params.split(", ");

                if(model.contains("}")){
                    String[] arrModel = model.split("}");
                    for(int i = 0; i < arrModel.length; i++) {
                        if(arrModel[i].contains("{")){
                            String param = arrModel[i].replaceFirst(".*\\{", "");
                            map.put(param, arrParams[i]);
                            model = model.replaceAll("\\$\\{"+param+"}", arrParams[i]);
                        }
                    }
                }
            }

            String content = smsSign.getTitle() + model;
            SmsLog smsLog = null;

            switch (smsModel.getModelType()) {
                case SysConstants.SMS_MODEL_TYPE_253:
                    break;
                case SysConstants.SMS_MODEL_TYPE_ALI:

                    int number = content.length() / 67 * arrPhones.length + 1;
                    if(number <= smsHost.getLeftNumber()) {
                        SendSmsResponse response = AliSms.sendSms(smsSign.getSmsKeyId(), smsSign.getSmsKeySecret(), smsModel.getSmsCode(),
                                phones, smsSign.getTitle(), JSON.toJSONString(map));
                        smsLog = new SmsLog(smsAuthorize.getId(), phones, JSON.toJSONString(map),
                                model, number, response.getBizId(), response.getCode(), response.getMessage());
                        if(response.getCode() != null && response.getCode().equals("OK")) {
                            // 记录发送短信日志
                            smsLog.setStatus(Boolean.TRUE);
                        }
                    } else {
                        smsLog = new SmsLog(smsAuthorize.getId(), phones, JSON.toJSONString(map),
                                model, NumberUtils.INTEGER_ZERO, null, null, "商户短信剩余数量不足.");
                    }
                    this.smsLogService.upsert(smsLog);
                    break;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
